package com.erp.user.controller;

import com.alibaba.fastjson.JSONObject;
import com.erp.user.domain.ErpDistributionUser;
import com.erp.user.domain.ErpDistributionUserBasicInfo;
import com.erp.user.domain.bo.ErpDistributionUserBo;
import com.erp.user.domain.param.DistributionParam;
import com.erp.user.domain.vo.ErpDistributionUserVo;
import com.erp.user.mapper.ErpDistributionUserBasicInfoMapper;
import com.erp.user.service.IErpDistributionUserBasicInfoService;
import com.erp.user.service.IErpDistributionUserService;
import com.ruoyi.common.core.annotation.RepeatSubmit;
import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.common.core.web.oldController.BaseController;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.RemoteSysConfigService;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import com.ruoyi.wallet.api.RemoteWalletService;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * 个人开户信息
 *
 * @author erp
 * @date 2023-05-09
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/distribution/user")
public class ErpUserInfoController extends BaseController {

    private final RemoteUserService remoteUserService;
    private final RemoteWalletService remoteWalletService;
    private final RemoteSysConfigService configService;

    @Resource
    IErpDistributionUserService distributionUserService;
    @Resource
    RabbitTemplate rabbitTemplate = SpringUtils.getBean(RabbitTemplate.class);
    @Resource
    IErpDistributionUserBasicInfoService distributionUserBasicInfoService;
    @Resource
    ErpDistributionUserBasicInfoMapper distributionUserBasicInfoMapper;

//    @GetMapping("/getErpAgentBranchInfo")
//    public R<Object> getErpAgentBranchInfo(String sellerLoginId) {
//        return iErpUserInfoService.getErpAgentBranchInfo(sellerLoginId);
//    }
//
//    @GetMapping("/getSellerList")
//    public R<Map<String,Object>> getSellerList() {
//        Map<String,Object> map=iErpUserInfoService.getSellerList();
//        return R.ok(map);
//    }
//
    /**
     * @Description: 查询个人开户信息列表
     * @Author: j.zh
     * @Date: 2024/5/4
     * @param bo
     * @param pageQuery
     * @return
     * @Version: 4.0.0
    **/
    @GetMapping("/list")
    public TableDataInfo<ErpDistributionUserVo> list(ErpDistributionUserBo bo, PageQuery pageQuery) {
        bo.setType(3);
        return distributionUserService.queryPageList(bo, pageQuery);
    }

    /**
     * @Description: 根据代理id查询旗下的所有用户
     * @Author: j.zh
     * @Date: 2024/5/4
     * @param parentAgentId
     * @return java.util.List<java.lang.Object>
     * @Version: 4.0.0
    **/
    @GetMapping("/getUserInfoByAgentId")
    public List<Object> getUserInfoByAgentId(String parentAgentId) {
        List<ErpDistributionUser> erpAgentInfos = distributionUserService.getListByIdAndType(Long.parseLong(parentAgentId), 2);
        List<Object> list = new ArrayList<>();
        if (erpAgentInfos != null) {
            erpAgentInfos.forEach(vo -> {
                Map<String, Object> map = new HashMap<>();
                Long id = vo.getDistributionUserId();
                R<Object> objectR = remoteUserService.selectUserById(vo.getUserId());
                String toJSONString = JSONObject.toJSONString(objectR.getData());
                SysUser sysUser = JSONObject.parseObject(toJSONString, SysUser.class);
                String corporateName = sysUser.getUserName() + " "
                        + distributionUserBasicInfoService.getByDistributionUserId(vo.getDistributionUserId()).getRealName() + " "
                        + vo.getIdentityCode();
                map.put("label", corporateName);
                map.put("value", id);
                list.add(map);
            });
        }
        return list;
    }
//
//    /**
//     * 导出个人开户信息列表
//     */
////    @SaCheckPermission("system:userInfo:export")
//    @Log(title = "个人开户信息", businessType = BusinessType.EXPORT)
//    @PostMapping("/export")
//    public void export(ErpUserInfoBo bo, HttpServletResponse response) {
//        List<ErpUserInfoVo> list = iErpUserInfoService.queryList(bo);
//        ExcelUtil<ErpUserInfoVo> excelUtil = new ExcelUtil<>(ErpUserInfoVo.class);
//        excelUtil.exportExcel(response,list, "个人开户信息","个人开户信息");
//    }
//
//    /**
//     * 获取个人开户信息详细信息
//     *
//     * @param id 主键
//     */
////    @SaCheckPermission("system:userInfo:query")
//    @GetMapping("/{id}")
//    public R<ErpUserInfoVo> getInfo(@NotNull(message = "主键不能为空")
//                                    @PathVariable Long id) {
//        return R.ok(iErpUserInfoService.queryById(id));
//    }

    /**
     * 创建用户,新增个人开户信息
     */
//    @SaCheckPermission("system:userInfo:add")
    @Log(title = "个人开户信息", businessType = BusinessType.INSERT)
    @Transactional
    @RepeatSubmit()
    @PostMapping("/add")
    public R<Void> add(@RequestBody DistributionParam param) {
        /** 注册系统用户 **/
        // 获取注册信息
        SysUser user = param.getUser();
        ErpDistributionUser parentDistributionUser = null;
        // 为新用户分配部门，如果是代理推荐，则用代理，分公司推荐用分公司
        if(param.getDistributionUser().getParentAgentId() != null){
            // 有所属代理，则用代理部门
            parentDistributionUser = distributionUserService.getDistributionUserById(param.getDistributionUser().getParentAgentId());
        }else {
            // 有所属公司
            parentDistributionUser = distributionUserService.getDistributionUserById(param.getDistributionUser().getParentBranchId());

        }
        R<Object> userObject = remoteUserService.selectUserById(parentDistributionUser.getUserId());
        if (userObject.getCode() != 200){
            return R.fail("获取用户失败");
        }
        String userStr = JSONObject.toJSONString(userObject.getData());
        user.setDeptId(JSONObject.parseObject(userStr, SysUser.class).getDeptId());

        // 为新用户分配角色：个人ERP
        user.setRoleIds(new Long[]{1732328402797199367L});
        user.setNickName(user.getUserName());
        // 注册系统用户
        remoteUserService.registerUser(user, SecurityConstants.INNER);
        R<LoginUser> userInfo = remoteUserService.getUserInfo(user.getUserName(), SecurityConstants.INNER);
        if (userInfo.getData() == null) {
            throw new RuntimeException("创建用户失败");
        }
        Long userId = userInfo.getData().getSysUser().getUserId();


        /** 注册分销用户 **/
        // 获取注册分销用户所需信息
        ErpDistributionUser distributionUser = param.getDistributionUser();

        // 设置推荐关系
        if (param.getDistributionUser().getParentId() == null) {
            // 说明没有直推个人
            distributionUser.setParentId(parentDistributionUser.getDistributionUserId());
            distributionUser.setParentIds(parentDistributionUser.getParentIds() + "," + parentDistributionUser.getDistributionUserId());
        }else {
            // 个人直推
            ErpDistributionUser directUser = distributionUserService.getDistributionUserById(param.getDistributionUser().getParentId());
            distributionUser.setParentIds(directUser.getParentIds() + "," + directUser.getDistributionUserId().toString());
        }

        distributionUser.setBindTime(new Date());

        BigDecimal distributionAmount = new BigDecimal("0");
        //得到一个Calendar的实例
        Calendar ca = Calendar.getInstance();
        //设置时间为当前时间
        ca.setTime(new Date());
        // 1:100元普通版，2:2800年版，3:12800年版，9先用后付，99免费版 其中，1为月版，2-3为年版，其他为永久版，-1为自定义
        switch (param.getDistributionUser().getBuyType().intValue()){
            case 1:
                ca.add(Calendar.MONTH, 1);
                distributionAmount = new BigDecimal(configService.getConfigKey("user_amount_1").getMsg());
                break;
            case 2:
                ca.add(Calendar.YEAR, 1);
                distributionAmount = new BigDecimal(configService.getConfigKey("user_amount_2").getMsg());
                break;
            case 3:
                ca.add(Calendar.YEAR, 1);
                distributionAmount = new BigDecimal(configService.getConfigKey("user_amount_3").getMsg());
                break;
            case 9:
            case 99:
                ca.add(Calendar.YEAR, 99);
                break;
            default:
                break;
        }
        // 设置有效期
        if (param.getDistributionUser().getBuyType().intValue() == -1){
            distributionUser.setExpirationTime(param.getDistributionUser().getExpirationTime());
        }else {
            distributionUser.setExpirationTime(ca.getTime());
        }

        distributionUser.setUserId(userId);
        // 生成身份代码
        distributionUser.setIdentityCode(distributionUserService.createIdentityCode(3));
        // 生成邀请码
        distributionUser.setInvitationCode(distributionUserService.createInvitationCode());
        // 分销员类型：个人
        distributionUser.setType(3);
        // 状态：正常
        distributionUser.setState(1);
        // 注册分销员
        Long distributionId = distributionUserService.insertDistributionUser(distributionUser);
        // 保存分销员基本信息
        ErpDistributionUserBasicInfo userBasicInfo = param.getDistributionUserBasicInfo();
        userBasicInfo.setDistributionUserId(distributionId);
        userBasicInfo.setUserMobile(user.getPhonenumber());
        distributionUserBasicInfoMapper.insert(userBasicInfo);

        // 初始化钱包
        remoteWalletService.initWallet(distributionId, userId, SecurityConstants.INNER);

        /** 分销计算 **/
        Map<String, Object> divideMap = new HashMap<>();
        // 分销类型
        divideMap.put("distributionType", 3);
        // 是否分销 TODO 获取不到，暂时写死
//        divideMap.put("isDistribution", param.getIsDistribution());
        divideMap.put("isDistribution", 0);
        // 分销金额
        divideMap.put("distributionAmount", distributionAmount);
        // 判断分销方式 TODO 自定义分销未做，默认固定方式
        divideMap.put("distributionMode",0);
        // 备注
        divideMap.put("remarks", "ERP：" + distributionId + "-" + param.getDistributionUserBasicInfo().getRealName());

        // ERP独有的数据
        // 所属分公司
        if (distributionUser.getParentBranchId() != null){
            divideMap.put("parentBranchId",distributionUser.getParentBranchId());
        }
        // 所属代理
        if (distributionUser.getParentAgentId() != null){
            divideMap.put("parentAgentId",distributionUser.getParentAgentId());
        }

        // 分发计算
        rabbitTemplate.convertAndSend("distribution-event-exchange",
                "distribution.sale.system.divide", JSONObject.toJSONString(divideMap));

        return R.ok();
    }

//    /**
//     * 修改个人开户信息
//     */
////    @SaCheckPermission("system:userInfo:edit")
//    @Log(title = "个人开户信息", businessType = BusinessType.UPDATE)
//    @RepeatSubmit()
//    @PostMapping("/edit")
//    public R<Void> edit(@RequestBody UserParam param) {
//        SysUser user = param.getUser();
//        String userName = user.getUserName();
//        ErpUserInfoBo info = param.getInfo();
//        // 获取分公司的用户的手机号
//        List<String> phoneList = new ArrayList<>();
//        List<String> emailList = new ArrayList<>();
//        List<ErpUserInfoVo> erpBranchOfficeInfos = userInfoMapper.selectVoList(new LambdaQueryWrapper<ErpUserInfo>()
//                .ne(ErpUserInfo::getUserId, info.getUserId()));
//        for (ErpUserInfoVo officeInfo : erpBranchOfficeInfos) {
//            Long userId = officeInfo.getUserId();
//            R<Object> objectR = userService.selectUserById(userId);
//            String toJSONString = JSONObject.toJSONString(objectR.getData());
//            SysUser sysUser = JSONObject.parseObject(toJSONString, SysUser.class);
//            phoneList.add(sysUser.getPhonenumber());
//            emailList.add(sysUser.getEmail());
//        }
//        R<Object> configKey = configService.getConfigKey("head_office_id");
//        String configKeyData = configKey.getMsg();
//        if (configKeyData.equals(info.getParentId())) {
//            info.setParentId(null);
//        }
//        user.setUserId(info.getUserId()); // 校验剔除该id
////        userService.checkUserAllowed(user);
////        userService.checkUserDataScope(user.getUserId());
////        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user))) {
////            return R.fail("修改用户'" + userName + "'失败，登录账号已存在");
////        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
////                && phoneList.contains(user.getPhonenumber())) {
////            return R.fail("修改用户'" + userName + "'失败，手机号码已存在");
////        } else if (StringUtils.isNotEmpty(user.getEmail())
////                && emailList.contains(user.getEmail())) {
////            return R.fail("修改用户'" + userName + "'失败，邮箱账号已存在");
////        }
//        R<Object> objectR = userService.selectUserById(info.getUserId());
//        String toJSONString = JSONObject.toJSONString(objectR.getData());
//        SysUser sysUser = JSONObject.parseObject(toJSONString, SysUser.class);
//        sysUser.setUserName(userName);
//        sysUser.setEmail(user.getEmail());
//        sysUser.setPhonenumber(user.getPhonenumber());
//        userService.updateUser(sysUser);
//        return toAjax(iErpUserInfoService.updateByBo(info));
//    }
//
//    /**
//     * 删除个人开户信息
//     *
//     * @param ids 主键串
//     */
////    @SaCheckPermission("system:userInfo:remove")
//    @Log(title = "个人开户信息", businessType = BusinessType.DELETE)
//    @GetMapping("/delete")
//    @Transactional
//    public R<Void> remove(String ids) {
//        List<String> collect = Arrays.stream(ids.split(",")).collect(Collectors.toList());
//        for (String s : collect) {
//            Long id = Long.parseLong(s);
//            ErpUserInfo info = userInfoMapper.selectById(id);
//            Long userId = info.getUserId();
////            userService.deleteUserById(userId);
//            userInfoMapper.deleteById(info);
//        }
//        return R.ok();
//    }

    /**
     * 获取用户有效期
     */
    @GetMapping("/getUserExpirationTime")
    public R<String> getUserExpirationTime(Long userId) {
        String expirationTime = distributionUserService.getUserExpirationTime(userId);
        if (expirationTime.matches("^\\d+$")){
            return R.ok("有效期内", expirationTime);
        }
        return R.fail(expirationTime);
    }



    /**
     * 个人历史数据推广提成数据重跑
     */
//    @GetMapping("/userInfoRerun")
//    public R<String> userInfoRerun() {
//        List<ErpUserInfo> list=userInfoMapper.selectList();
//        for (ErpUserInfo info:list){
//            if(StringUtils.isEmpty(info.getParentId())&&StringUtils.isEmpty(info.getBranchId())){
//                continue;
//            }
//            // 在所属部门加入用户
//            String branchId = info.getBranchId();
//            String agentId = info.getAgentId();
//
//            // 获取到上级的父类ids
//            String parentId = info.getParentId();
//            String parentCode = null; // 推荐人的代码
//            SysUser sysUser = new SysUser();
//            Long deptId = 0L;
//            if (StringUtils.isNotEmpty(parentId)) {
//                ErpUserInfoVo userInfoVo = iErpUserInfoService.queryById(Long.parseLong(parentId));
//                // 如果直推人是个人,被推人的部门是直推人的部门
//                parentCode = userInfoVo.getCode();
//            } else if (StringUtils.isNotEmpty(agentId)) {
//                ErpAgentInfoVo agentInfoVo = agentInfoService.queryById(Long.valueOf(agentId));
//                parentCode = agentInfoVo.getCode();
//            } else if (StringUtils.isNotEmpty(branchId)) {
//                ErpBranchOfficeInfoVo officeInfoVo = branchOfficeInfoService.queryById(Long.valueOf(branchId));
//                parentCode = officeInfoVo.getCode();
//            }
//            R<Object> configKey = configService.getConfigKey("user_amount");
//            String agentAmount = configKey.getMsg();
//            BigDecimal amount = new BigDecimal(agentAmount);
//            // 4. 访问分销接口
//            /**
//             * 分佣
//             * @param userId        被推广用户id
//             * @param userType      被推广用户类型（1分公司 2代理 3个人）
//             * @param recommendTime 推荐时间
//             * @param parentCode      推荐客户编码
//             * @param amount        金额
//             * @param isDivide      是否分佣 0否 1是
//             * @param orderNo       订单号
//             */
//            distributePropService.divide(info.getUserId(), 3, info.getCreateTime(), parentCode, amount, 0, info.getCode());
//
//        }
//
//        return R.ok();
//    }

    @GetMapping("/getLogin")
    public R<Object> getLogin() {
        Long userId = SecurityUtils.getUserId();
        System.out.println("缓存" + userId + SecurityUtils.getUsername());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        System.out.println(loginUser.getUserid() + loginUser.getUsername());
        return R.ok();
    }

}
